import matplotlib.pyplot as plt
import pyplotCh

pyplotCh.set_ch()

decisionNode = dict(boxstyle="round4", fc="0.8")
leafNode = dict(boxstyle="round4", fc="0.8")
arrow_args = dict(arrowstyle="<-")


def plotNode(nodeTxt, centerPt, parentPt, nodeType):
    createPlot.ax1.annotate(nodeTxt, xy=parentPt, xycoords='axes fraction', \
                            xytext=centerPt, textcoords='axes fraction', \
                            va="center", ha="center", bbox=nodeType, \
                            arrowprops=arrow_args)


def getLeafCount(tree): # 以字典表示的树形结构
    leafCount = 0
    rootNode = list(tree.keys())[0]
    rootNodeValue = tree[rootNode]      # Here should be a dict
    for keys in rootNodeValue.keys():
        if type(rootNodeValue[keys]).__name__=='dict':   # if the value is a subtree
            leafCount += getLeafCount(rootNodeValue[keys])
        else:
            leafCount += 1
    return leafCount


def getTreeDepth(tree): # 以字典表示的树形结构
    depth = 1           # Depth starts with 1 (root node)
    rootNode = list(tree.keys())[0]
    rootNodeValue = tree[rootNode]      # Here should be a dict
    maxSubtreeDepth = 0        # Max depth of leaf or subtree
    for keys in rootNodeValue.keys():
        if type(rootNodeValue[keys]).__name__=='dict':   # if the value is a subtree
            subtreeDepth = getTreeDepth(rootNodeValue[keys])
        else:
            subtreeDepth = 1
        if maxSubtreeDepth < subtreeDepth: maxSubtreeDepth = subtreeDepth   # choose the max depth of subtree to addMaxDepth
    depth += maxSubtreeDepth
    return depth

def plotMidText(cntrPt, parentPt, txtString):
    xMid = (parentPt[0]-cntrPt[0])/2.0 + cntrPt[0]
    yMid = (parentPt[1] - cntrPt[1]) / 2.0 + cntrPt[1]
    createPlot.ax1.text(xMid, yMid, txtString)

def plotTree(myTree, parentPt, nodeTxt):
    # plotTree.xOff = 0.0
    # plotTree.yOff = 0.0
    numLeafs = getLeafCount(myTree)
    depth = getTreeDepth(myTree)
    firstStr = list(myTree.keys())[0]
    cntrPt = (plotTree.xOff + (1.0 + float(numLeafs))/2.0/plotTree.TotalW, \
              plotTree.yOff)
    plotMidText(cntrPt, parentPt, nodeTxt)
    plotNode(firstStr, cntrPt, parentPt, decisionNode)
    secondDict = myTree[firstStr]
    plotTree.yOff = plotTree.yOff - 1.0/plotTree.TotalD
    for key in secondDict.keys():
        if type(secondDict[key]).__name__=='dict':
            plotTree(secondDict[key], cntrPt, str(key))
        else:
            plotTree.xOff = plotTree.xOff + 1.0/plotTree.TotalW
            plotNode(secondDict[key], (plotTree.xOff, plotTree.yOff), \
                     cntrPt, leafNode)
            plotMidText((plotTree.xOff, plotTree.yOff), cntrPt, str(key))
    plotTree.yOff = plotTree.yOff + 1.0/plotTree.TotalD

def createPlot(inTree):
    fig = plt.figure(1, facecolor='white')
    fig.clf()
    axprops = dict(xticks=[], yticks=[])
    createPlot.ax1 = plt.subplot(111, frameon=False, **axprops)
    plotTree.TotalW = float(getLeafCount(inTree))
    plotTree.TotalD = float(getTreeDepth(inTree))
    plotTree.xOff = -0.5/plotTree.TotalW
    plotTree.yOff = 1.0
    plotTree(inTree, (0.5, 1.0), '')
    plt.show()